import { getDics, login, logout, queryCurrentAccountPeriod } from '@/api/user'
import { getUserPermissions } from '@/api/role'
import { queryMerchantListApi } from '@/api/merchant/merchant-manage/merchant-list'
import { queryMerchantDetailApi } from '@/api/merchant/merchant-manage/merchant-detail'
import { queryCurrencySymbolApi } from '@/api/merchant/merchant-config/payment-channel-config'
// import { Session } from '@/utils/compose'
import { Storage } from '@/utils/compose'
import short from 'short-uuid'
import Cookies from 'js-cookie'
import globalDict from '@/dict'
import {
	clearCookie,
	getToken,
	getUserInfo,
	removeToken,
	setNickName,
	setToken,
	setUserInfo,
	setUsername
} from '@/utils/auth'
import router, { resetRouter } from '@/router'
import md5 from 'js-md5'
import dataHandle from '@/utils/encrypt'
import dayjs from 'dayjs'
import { Message } from 'element-ui'

const state = {
	token: getToken(),
	roles: [],
	rolesIds: [],
	name: '',
	username: '',
	// 新增用户审核数量
	auditNewUser: '',
	// 会员资料变更审核数量
	auditUpdateInfoUser: '',
	// 新增代理数量
	auditProxyAdd: '',
	// 代理资料变更审核数量
	auditUpdateInfoAgent: '',
	// 会员转代审核数量
	auditMemberTransferUser: '',
	// 佣金审核数量
	proxyCommissionAuditCount: '',
	// 开启代理入口审核
	openProxyReview: '',
	// 代理换线审核
	upTopProxyReview: '',
	// 会员提款审核
	auditMemberWithdrawUser: '',
	// 代理提款审核
	auditProxyWithdrawAgent: '',
	// 会员人工加额审核
	auditMemberArtificialAddUser: '',
	// 代理人工加额审核
	auditProxyArtificialAddAgent: '',
	// 佣金审核
	auditProxyCommissionAgent: '',
	// 返点审核
	auditProxyRebateAgent: '',
	// 红利审核
	auditMemberActivityBonusUser: '',
	// 会员账单提现下分审核
	auditMemberWithdrawSubUser: '',
	// 新增商户审核
	auditMerchantAdd: '',
	// 代理收益审核
	proxyIncomeAudit: '',
	// 总代分红审核
	dividendAuditCount: '',
	myDownloadBadge: false, // 我的下载小红点
	totalCreditAmount: '',
	nickName: '',
	userInfo: getUserInfo(),
	avatar: '',
	globalDics: {},
	datas: {},
	// 商户列表
	merchantList: [],
	// 商户信息
	merchantInfo: {},
	currencySymbol: '',
	// 最近一次账单结算时间
	currentAccountPeriod: {
		periodStDate: dayjs(),
		periodEnDate: dayjs()
	}
}

const mutations = {
	SET_AUDIT: (state, { value, type }) => {
		state[type] = value
	},
	SET_TOKEN: (state, token) => {
		state.token = token
	},
	SET_GLOBAL_DICT: (state, dics) => {
		state.globalDics = Object.assign({}, dics, {
			language: [
				{
					code: 'zh_CN',
					description: '中文'
				}
			],
			currency: [{ code: 'USDT', description: 'USDT' }]
		})
	},
	SET_USERINFO: (state, userInfo) => {
		state.userInfo = userInfo
	},
	SET_MYDOWNLOADBADGE: (state, type) => {
		state.myDownloadBadge = type
	},
	SET_NAME: (state, name) => {
		state.nickName = name
	},
	SET_ACCOUNT: (state, name) => {
		state.username = name
	},
	SET_AVATAR: (state, avatar) => {
		state.avatar = avatar
	},
	SET_ROLES: (state, roles) => {
		state.roles = roles
	},
	SET_ROLES_IDS: (state, rolesIds) => {
		state.rolesIds = rolesIds
	},
	SET_DATA: (state, datas) => {
		if (datas) {
			state.datas = datas
		}

		const { countryType, gametype } = state.datas
		if (Cookies.get('language') === 'en') {
			state.datas.countryType = countryType.map((i) => {
				return {
					...i,
					type: i.englishText
				}
			})
			state.datas.gametype = gametype.map((i) => {
				return {
					...i,
					type: i.englishText
				}
			})
		}
		if (Cookies.get('language') === 'zh') {
			state.datas.countryType = countryType.map((i) => {
				return {
					...i,
					type: i.text
				}
			})
			state.datas.gametype = gametype.map((i) => {
				return {
					...i,
					type: i.text
				}
			})
		}
	},
	SET_MERCHANT_LIST: (state, list) => (state.merchantList = list),
	SET_MERCHANT_INFO: (state, info) => (state.merchantInfo = info),
	SET_CURRENCY_SYMBOL: (state, datas) => {
		if (datas) {
			state.currencySymbol = datas[0]?.symbol
		}
	},
	SET_CURRNET_ACCOUNT_PERIOD: (state, data) => {
		state.currentAccountPeriod.periodStDate = data.start
		state.currentAccountPeriod.periodEnDate = data.end
	}
}

const actions = {
	setAudit({ commit }, { value, type }) {
		commit('SET_AUDIT', { value, type })
	},
	login2({ commit }, userInfo) {
		return new Promise((resolve, reject) => {
			commit('SET_TOKEN', 'data.token')
			setUsername('开发账号')
			localStorage.setItem('password', 'aabb1122')
			setToken('data.token')
			resolve()
		})
	},
	login({ commit }, userInfo) {
		const { username, password, googleAuthCode, merchantCode } = userInfo
		return new Promise((resolve, reject) => {
			login({
				username: username.trim(),
				password: md5(username.trim() + password.trim()),
				googleAuthCode,
				merchantCode,
				type: '1'
			})
				.then((response) => {
					if (response && response.code === 200) {
						const { data } = response
						commit('SET_TOKEN', data.token)
						commit('SET_ACCOUNT', data.userInfo.username)
						commit('SET_NAME', data.userInfo.nickName)
						commit('SET_USERINFO', data.userInfo)
						setToken(data.token)
						setUserInfo(data.userInfo)
						setUsername(data.userInfo.username)
						setNickName(data.userInfo.nickName)
						localStorage.setItem('username', username)
						localStorage.setItem(
							'c2',
							dataHandle.encryptData2(password)
						)
						localStorage.setItem(
							'd1',
							dataHandle.encryptData2(data.userInfo.id)
						)
						resolve(data)
					} else {
						reject(response.data)
					}
				})
				.catch((error) => {
					reject(error)
				})
		})
	},

	getDictList({ commit, state }) {
		commit('SET_GLOBAL_DICT', globalDict)
		getDics().then(({ data }) => {
			// commit('SET_GLOBAL_DICT', data)
		})
	},

	// 获取当前登录账号的商户信息
	async getMerchantInfo({ commit, state }) {
		const { data } = await queryMerchantDetailApi({
			id: state.userInfo.merchantId + ''
		})
		commit('SET_MERCHANT_INFO', data || {})
	},

	// 获取商户列表
	async getMerchantList({ commit, state }) {
		const { data } = await queryMerchantListApi({})
		commit('SET_MERCHANT_LIST', data || [])
	},

	// 获取货币符号
	async getCurrencySymbol({ commit, state }) {
		const { data } = await queryCurrencySymbolApi({})
		const symbolSign = data ? data?.symbol : '$'
		Storage.set('currencySymbol', symbolSign)
		commit('SET_CURRENCY_SYMBOL', data || [])
	},

	logout2({ dispatch }) {
		return new Promise((resolve) => {
			dispatch('clearAllCaches')
			router.push('/login')
			resolve()
		})
	},
	logout({ commit, dispatch, state }) {
		return new Promise((resolve, reject) => {
			logout(state.token)
				.then(() => {
					dispatch('clearAllCaches')
					resolve()
				})
				.catch((error) => {
					reject(error)
				})
		})
	},
	clearAllCaches({ commit, dispatch }) {
		commit('SET_TOKEN', '')
		dispatch('permission/clearRoutes', {}, { root: true })
		removeToken()
		clearCookie()
		resetRouter()
		// 退出时清除所有页签
		dispatch('tagsView/delAllViews', {}, { root: true })
		// 处理拖拽表格退出登录后保存拖拽的表头数据
		const newTableHeadData = Storage.get('commonTableKey')
		const murmur = Storage.get('finger')
		window.localStorage.clear()
		window.sessionStorage.clear()
		Storage.set('commonTableKey', newTableHeadData)
		Storage.set('finger', murmur)
	},
	// remove token
	resetToken({ commit }) {
		return new Promise((resolve) => {
			commit('SET_TOKEN', '')
			clearCookie()
			removeToken()
			resolve()
		})
	},
	getRoles({ commit }) {
		return new Promise((resolve, reject) => {
			getUserPermissions()
				.then(({ data }) => {
					const result = []
					window.localStorage.setItem('role', JSON.stringify(data))
					loop(data, result)
					commit('SET_ROLES', data)
					commit('SET_ROLES_IDS', result)
					resolve(data)
				})
				.catch((err) => reject(err))
		})
	},
	changeDataLanguage({ commit }) {
		return new Promise((resolve) => {
			commit('SET_DATA', null)
			resolve()
		})
	},
	async updateCurrentAccountPeriod({ commit }) {
		/**
		 * Check is period date should be update
		 * Potential issue:
		 * This datetime without timezone
		 * If there is a user from a different timezone with the server, this checking could not working as our excepted
		 */
		if (!dayjs().isAfter(state.currentAccountPeriod.periodEnDate)) return
		const { data } = await queryCurrentAccountPeriod({})
		const start = dayjs(
			`${data.periodStDate}${data.periodStTime || '000000'}`,
			'YYYYMMDDHHmmss'
		)
		const end = dayjs(
			`${data.periodEnDate}${data.periodEnTime || '235959'}`,
			'YYYYMMDDHHmmss'
		)
		if (!start.date() || !end.date()) {
			// 拦截导出错误提示
			Message.closeAll()
			Message({
				message: 'Error: 本账期周期时间获取失败！',
				type: 'error'
			})
			return
		}
		commit('SET_CURRNET_ACCOUNT_PERIOD', { start, end })
	}
}

function loop(data, result) {
	if (!data || data.length === 0) return []

	data.forEach((i) => {
		result.push(i.id)
		if (i.children && i.children.length > 0) {
			loop(i.children, result)
		}
	})
}

export default {
	namespaced: true,
	state,
	mutations,
	actions
}
